package com.c2b.algorithm.newcoder.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * <a href="https://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635?tpId=295&tqId=2291302&ru=%2Fpractice%2F2b317e02f14247a49ffdbdba315459e7&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj">二叉树的前序遍历</a>
 * <p>
 * 给你二叉树的根节点 root ，返回它节点值的 前序 遍历。<br>
 * <p>
 * 数据范围：二叉树的节点数量满足1≤n≤100  ，二叉树节点的值满足1≤val≤100  ，树的各节点的值各不相同
 * </p>
 * <pre>
 *      1
 *       \
 *        2
 *       /
 *      3
 *
 * 输入：{1,#,2,3}
 * 返回值：[1,2,3]
 * </pre>
 *
 * @author c2b
 * @since 2023/3/13 14:57
 */
public class BM0023PreorderTraversal_S {

    /**
     * 前序遍历：借助栈
     */
    public int[] preorderTraversal(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        List<Integer> resList = new ArrayList<>();
        while (!stack.empty()) {
            TreeNode currNode = stack.pop();
            resList.add(currNode.val);
            // 先右再左
            if (currNode.right != null) {
                stack.push(currNode.right);
            }
            if (currNode.left != null) {
                stack.push(currNode.left);
            }
        }
        int[] resArray = new int[resList.size()];
        for (int i = 0; i < resList.size(); i++) {
            resArray[i] = resList.get(i);
        }
        return resArray;
    }

    public int[] preorderTraversal2(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        List<Integer> resList = new ArrayList<>();
        resList = recursion(resList, root);
        int[] resArray = new int[resList.size()];
        for (int i = 0; i < resList.size(); i++) {
            resArray[i] = resList.get(i);
        }
        return resArray;
    }

    private List<Integer> recursion(List<Integer> resList, TreeNode treeNode) {
        if (treeNode == null) {
            return resList;
        }
        resList.add(treeNode.val);
        if (treeNode.left != null) {
            recursion(resList, treeNode.left);
        }
        if (treeNode.right != null) {
            recursion(resList, treeNode.right);
        }
        return resList;
    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(4);
        treeNode.left = new TreeNode(5);
        treeNode.right = new TreeNode(3);
        treeNode.left.left = new TreeNode(6);
        treeNode.right.left = new TreeNode(1);
        treeNode.right.right = new TreeNode(0);
        treeNode.right.left.left = new TreeNode(9);

        BM0023PreorderTraversal_S s_bm0023PreorderTraversal = new BM0023PreorderTraversal_S();
        for (int i : s_bm0023PreorderTraversal.preorderTraversal2(treeNode)) {
            System.out.println(i);
        }
    }
}
